from PyQt6.QtWidgets import QMainWindow, QListWidget, QVBoxLayout, QWidget, QPushButton, QHBoxLayout, QMessageBox
from git_utils.git_handler import GitRepoHandler
from ui.commit_detail import CommitDetailWindow
from git.objects import Commit
import logging

logger = logging.getLogger(__name__)


class GitCommitViewer(QMainWindow):
    def __init__(self, repo_path):
        super().__init__()
        self.setWindowTitle("Git 提交浏览器")
        self.setGeometry(200, 200, 800, 600)

        self.repo_handler = GitRepoHandler(repo_path)
        self.init_ui()

    def init_ui(self):
        central_widget = QWidget()
        layout = QVBoxLayout()

        self.commit_list = QListWidget()
        self.commit_list.itemClicked.connect(self.show_commit_detail)

        self.analyze_button = QPushButton("AI 分析此提交")
        self.analyze_button.clicked.connect(self.analyze_commit)

        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(self.analyze_button)

        layout.addWidget(self.commit_list)
        layout.addLayout(button_layout)

        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        self.load_commits()

        self.detail_windows = []  # 保持子窗口引用，防止被回收

    def load_commits(self):
        try:
            self.commits: list[Commit] = self.repo_handler.get_commits()
            self.commit_list.clear()
            for c in self.commits:
                self.commit_list.addItem(f"{c.hexsha[:7]}: {c.summary}")
        except Exception as e:
            logger.exception("加载提交失败")
            QMessageBox.critical(self, "错误", f"无法加载提交记录：{str(e)}")

    def show_commit_detail(self, item):
        index = self.commit_list.currentRow()
        commit = self.commits[index]
        logger.info(f"创建窗口：{commit.hexsha[:7]}({commit.summary})")
        detail_window = CommitDetailWindow(commit)
        detail_window.show()
        detail_window.raise_()
        detail_window.activateWindow()

        # 保持引用，避免被垃圾回收
        self.detail_windows = [w for w in self.detail_windows if w.isVisible()]
        self.detail_windows.append(detail_window)

    def analyze_commit(self):
        index = self.commit_list.currentRow()

        if index == -1:
            logger.warning("用户点击了 'AI 分析此提交'，但未选择任何提交")
            QMessageBox.information(self, "提示", "请先选择一个提交。")
            return

        commit: Commit = self.commits[index]
        logger.info(f"用户请求分析提交：{commit.hexsha[:7]} - {commit.summary}")

        self.show_commit_detail(None)
